<template>
  <ContainerContent :loading="loading" :pagination="pagination" @run="run">
    <template #header>
      <a-button type="primary" @click="visible = true">
        <i-icons-btn-add />
        创建规则
      </a-button>
      <CloudFilterBar
        v-model="params"
        :run="run"
        :schemes="filterSchemes"></CloudFilterBar>
    </template>
    <a-table
      ref="tableRef"
      v-bind="commonTableProps"
      :columns="columns"
      :data="data"
      row-key="id"
      @sorter-change="onSorterChange">
      <template #sort>
        <i-icons-draggable class="drag-icon" />
      </template>
      <template #skip_module="{ record }">
        {{ getSkipModuleDesc(record?.module_config?.skip_module) }}
      </template>
      <template #status="{ record }">
        <a-switch
          :model-value="record.status"
          :checked-value="1"
          :unchecked-value="2"
          size="small"
          :before-change="
            (val: number) => handleBeforeChange(val, record)
          "></a-switch>
      </template>
      <template #action="{ record }">
        <a-link :hoverable="false" @click="open(record)"> 编辑 </a-link>
        <a-link
          status="danger"
          :hoverable="false"
          @click="handDelete(record.id)">
          删除
        </a-link>
      </template>
    </a-table>
    <add-rule-dialog
      v-model:visible="visible"
      :record="ruleData"
      :id="id"
      :list="data || []"
      :show-priority="
        (data?.length > 0 && !ruleData) || (ruleData && data?.length > 1)
      "
      @refresh="run" />
  </ContainerContent>
</template>
<script lang="ts" setup>
import type { WafListItem } from '@/apis/model/waf'
import {
  deleteApiWafApi,
  getApiWafQueryApi,
  updateApiWafPriorityApi,
  updateApiWafStatusApi
} from '@/apis/modules/waf'
import ContainerContent from '@/components/ContentContainer.vue'
import type { CloudFilterBarState } from '@/components/filter-bar/types'
import { getOptionsLabel } from '@/utils'
import { commonTableProps } from '@/utils/table'
import Sortable from 'sortablejs'
import AddRuleDialog from './AddRuleDialog.vue'
import useTableColumn from './column'
import { useConfigStore } from '@/stores/config'
const route = useRoute()
const id = computed(() => route.params.id as string)
const params = ref<CloudFilterBarState>({
  order: 'asc',
  sort: 'priority',
  scope: 2,
  module: 3,
  bind_id: id.value
})
const tableRef = ref()
const { visible, open, data: ruleData } = usePopup()

const { columns, filterSchemes } = useTableColumn()
const { data, loading, run, pagination } = useListRequest(getApiWafQueryApi, {
  params,
  immediate: false
})
const { createSortChange } = useTable(run, data)
const onSorterChange = createSortChange(params)

const getSkipModuleDesc = (skipOptions: any[]) => {
  const arr = [] as string[]
  skipOptions.forEach((item: any) => {
    arr.push(getOptionsLabel(skipModuleOptions, item))
  })
  return arr.join(',')
}
const handleBeforeChange = (status: number, row: WafListItem) => {
  return new Promise((resolve) => {
    if (status === 1) {
      CloudModal.confirm(
        {
          content: '确定要开启此规则吗？'
        },
        async () => {
          await updateApiWafStatusApi({ id: row.id, status } as any)
          ToastUtils.success('操作成功')
          run()
          resolve(void 0)
        },
        () => {
          resolve(void 0)
        }
      )
    } else {
      CloudModal.error(
        {
          content: '确定要关闭此规则吗？'
        },
        async () => {
          await updateApiWafStatusApi({ id: row.id, status } as any)
          ToastUtils.success('操作成功')
          run()
          resolve(void 0)
        },
        () => {
          resolve(void 0)
        }
      )
    }
  })
}

const handDelete = (id: string) => {
  CloudModal.error(
    {
      content: '该操作会删除此规则，确认删除？',
      okText: '删除'
    },
    async () => {
      await deleteApiWafApi({ id })
      ToastUtils.success('删除成功')
      run!()
    }
  )
}
watchEffect(() => {
  run({ bind_id: id.value })
})
const changeRule = async (id: string, priority: number) => {
  await updateApiWafPriorityApi({ id, priority })
  ToastUtils.success('操作成功')
  run()
}
onMounted(async () => {
  const customRulesId = localStorage.getItem('customRulesId')
  if (customRulesId) {
    params.value.id = customRulesId
    localStorage.setItem('customRulesId', '')
    localStorage.setItem('logModule', '')
  }
  await nextTick()
  const el = (tableRef.value.$el as HTMLElement).querySelector('tbody')
  Sortable.create(el, {
    animation: 300,
    //设置指定列作为拖拽
    handle: '.drag-icon',
    forceFallBack: true,
    onEnd(evt: { newIndex: number; oldIndex: number }) {
      const { newIndex, oldIndex } = evt
      if (newIndex === oldIndex) {
        return
      }
      const id = data.value[oldIndex].id!
      const priority = data.value[newIndex].priority!
      changeRule(id, priority)
    }
  })
  useConfigStore().getCondition({ module: 3 })
})
</script>

<style lang="less" scoped></style>
